package com.SpringBoot.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.SpringBoot.user.pojo.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.authority.SimpleGrantedAuthority;


import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 当前数据结构 就是对原始user进行的封装
 * SpringSecurity会读取当前结构中信息 进行认证
 */
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyUserDetails implements UserDetails {
    private User user;

    private List<String> menuList;
    @JsonIgnore
    private List<GrantedAuthority> authorities;
    @Override
    @JsonIgnore
    public Collection<GrantedAuthority> getAuthorities() {
        //如果authorities为null 则通过menuList 构建权限集合
        if(authorities == null){
            authorities = menuList.stream()
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
